//
//  SocketDispatch.m
//  dongfangyixin20151027
//
//  Created by longziyuan on 15-3-9.
//
//

#import "SocketDispatch.h"
#import "Infro.h"
#import "GlobalVar.h"
#import "ASIFormDataRequest.h"
//
static SocketDispatch* shareInstance=nil;


@implementation SocketDispatch

+(SocketDispatch*)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance=[[self alloc]init];
    });
    return shareInstance;
}

-(void)socketCheck
{
    timeArr=[[NSMutableArray alloc]init];
    NSArray* theArr=[GlobalVar getZhongzhuanUrls];
    urlsDic=[[NSMutableDictionary alloc]init];
    if ([theArr count]>0)
    {
        for (NSString* url in theArr)
        {
            url=[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSArray* componentArr=[url componentsSeparatedByString:@"/"];
            NSString* urlMainPart=componentArr[2];
            [urlsDic setObject:url forKey:urlMainPart];
        }
    }else
    {
        /*
        [urlsDic setObject:@"http://122.114.120.26/sync" forKey:@"122.114.120.26:80"];
        [urlsDic setObject:@"http://59.63.182.181:8008" forKey:@"59.63.182.181:8008"];
        [urlsDic setObject:@"http://171.34.30.181:8008" forKey:@"171.34.30.181:8008"];
        [urlsDic setObject:@"http://61.146.138.151:8002/appapi" forKey:@"61.146.138.151:8002"];
        [urlsDic setObject:@"http://121.40.86.219:8002/appapi" forKey:@"121.40.86.219:8002"];
        [urlsDic setObject:@"http://119.147.137.16:8002/appapi" forKey:@"119.147.137.16:8002"];
        [urlsDic setObject:@"http://119.147.137.79:8002/appapi" forKey:@"119.147.137.79:8002"];
        [urlsDic setObject:@"http://183.237.48.232:8002/appapi" forKey:@"183.237.48.232:8002"];
        [urlsDic setObject:@"http://61.145.116.124:8008/appapi" forKey:@"61.145.116.124:8008"];
        [urlsDic setObject:@"http://122.114.58.59:8002/appapi" forKey:@"122.114.58.59:8002"];
        [urlsDic setObject:@"http://222.180.162.61:8008/appapi" forKey:@"222.180.162.61:8008"];
        [urlsDic setObject:@"http://113.207.26.202:8008/appapi" forKey:@"113.207.26.202:8008"];
         */
        [urlsDic setObject:@"http://121.40.86.219:8002/appapi" forKey:@"121.40.86.219:8002"];
        [urlsDic setObject:@"http://119.147.137.16:8002/appapi" forKey:@"119.147.137.16:8002"];
        [urlsDic setObject:@"http://119.147.137.79:8002/appapi" forKey:@"119.147.137.79:8002"];
        [urlsDic setObject:@"http://61.145.116.124:8008/appapi" forKey:@"61.145.116.124:8008"];
        [urlsDic setObject:@"http://122.114.58.59:8002/appapi" forKey:@"122.114.58.59:8002"];
        [urlsDic setObject:@"http://121.41.25.193:8002/appapi" forKey:@"121.41.25.193:8002"];
        [urlsDic setObject:@"http://222.180.162.61:8008/appapi" forKey:@"222.180.162.61:8008"];
        [urlsDic setObject:@"http://113.207.26.202:8008/appapi" forKey:@"113.207.26.202:8008"];
        [urlsDic setObject:@"http://121.42.144.46:80/appapi" forKey:@"121.42.144.46:80"];
    }
    is_Lock=YES;
    checkFailCount=0;
    checkTotalCount=0;
    for (int i=0; i<[[urlsDic allKeys] count]; i++)
    {
        Infro* info=[[Infro alloc]init];
        NSString* ipAndPort=[[urlsDic allKeys] objectAtIndex:i];
        NSArray* ipAndPortArr=[ipAndPort componentsSeparatedByString:@":"];
        UInt64 pre=[GlobalVar getTimeChuo];
        info.theIP=ipAndPort;
        info.starTime=pre;
        //NSLog(@"请求之前的时间:%llu,对应的:%@",info.starTime,ipAndPort);
        [timeArr addObject:info];
        @try
        {
            AsyncSocket*  socket=[[AsyncSocket alloc] initWithDelegate:self];
            [socket connectToHost:ipAndPortArr[0] onPort:[[ipAndPortArr objectAtIndex:1] intValue]error:nil];
            [socket setUserData:i];
            [socket readDataWithTimeout:30.0 tag:i];
        }
        @catch (NSException *exception)
        {
            NSLog(@"the exception:%@",exception);
        }
        @finally
        {
            //NSLog(@"go on");
        }
    }
}

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    checkTotalCount++;
    NSString* backIPAndPort=[NSString stringWithFormat:@"%@:%hu",host,port];
    //NSLog(@"AsyncSocket连接成功＝backIPAndPort==:%@",backIPAndPort);
    for (Infro* inf in timeArr)
    {
        if ([inf.theIP isEqualToString:backIPAndPort])
        {
           // NSLog(@"开始时间:%llu",inf.starTime);
            UInt64 after=[GlobalVar getTimeChuo];
            inf.endTime=after;
            //NSLog(@"结束时间:%llu",inf.endTime);
            UInt64 cha=[GlobalVar preRequestTime:inf.starTime  AndAfterRequestTime:after];
            //NSLog(@"差值==:%llu",cha);
            NSString* result=[NSString stringWithFormat:@"%@|%llu\n",inf.theIP,cha];
            //NSLog(@"结果是===:%@",result);
           [GlobalVar writeTheInfoToTheLocal:result];
            break;
        }
    }
    //NSLog(@"theCount====%d  %d",theCount,timeArr.count);
    if (is_Lock==YES)
    {
        is_Lock=NO;
        NSString* zuiyouUrl=[NSString stringWithFormat:@"%@:%hu",host,port];
        NSString* theUl=[urlsDic objectForKey:zuiyouUrl];
        NSLog(@"最好的url====:%@",theUl);
        NSString* theBestResult=[NSString stringWithFormat:@"#%@ \n",theUl];
        [GlobalVar writeTheInfoToTheLocal:theBestResult];
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        //用选择好的最优url地址去绑定
        [defaults setObject:theUl forKey:@"BEST"];
        [defaults synchronize];
        
        if (self.delegate)
        {
            
            [self.delegate checkTheBestIpComplete];
        }
    }
    [sock setDelegate:nil];
    [sock disconnect];
    [sock release];
    [self checkUploadFile];
}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"sorry the connect is failure %ld",sock.userData);

}
-(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    checkFailCount++;
    checkTotalCount++;
    NSArray*arr = [urlsDic allKeys];
    NSString*ip=arr[sock.userData];
    NSString* result=[NSString stringWithFormat:@"%@|%@\n",ip,err];
    [GlobalVar writeTheInfoToTheLocal:result];
    if (checkFailCount==urlsDic.count)
    {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接超时,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertView.tag=200;
        [alertView show];
    }
    [self checkUploadFile];
}
-(void)checkUploadFile
{
    if (checkTotalCount==urlsDic.count && checkFailCount<checkTotalCount)
    {
        NSString* isUpdateFile=[[NSUserDefaults standardUserDefaults] objectForKey:@"UPDATEFILE"];
        //1表示要上传件到后台
        if ([isUpdateFile intValue]==1)
        {
            NSFileManager* fileManager=[NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:[GlobalVar getFilePath:@"result.txt"]])
            {
                NSString* result=[NSString stringWithContentsOfFile:[GlobalVar getFilePath:@"result.txt"] encoding:NSUTF8StringEncoding error:nil];
                if ([result length]>0)
                {
                    [self uploadFile];
                }
            }
        }

    }
}
//上传socket并发情况文件
-(void)uploadFile
{
    ASIFormDataRequest* request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",@"http://222.180.162.61:8008/abnormal.php"]]];
    [request setDelegate:self];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    [request setPostValue:SOFT_ID forKey:@"softid"];
    [request setPostValue:[GlobalVar loginUserKey] forKey:@"mobile"];
    [request setPostValue:@"abnormal" forKey:@"act"];
    [request setFile:[GlobalVar getFilePath:@"result.txt"] forKey:@"abnfile"];
    [request  setDidFinishSelector:@selector(upLoadSuccess:)];
    [request setDidFailSelector:@selector(upLoadFail:)];
    [request startAsynchronous];
}

-(void)upLoadSuccess:(ASIHTTPRequest*)request
{
    NSString* upLoadResult=[request responseString];
    NSLog(@"上传文件 result:%@",upLoadResult);
    NSArray* upLoadInfroArr=[upLoadResult componentsSeparatedByString:@"|"];
    if ([upLoadInfroArr count]==2)
    {
        NSString* code=[upLoadInfroArr objectAtIndex:0];
        if ([code isEqualToString:@"1"])
        {
            NSLog(@"上传文件成功!");
            NSError* error;
            NSFileManager* fileManager=[NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:[GlobalVar getFilePath:@"result.txt"]])
            {
                BOOL success=[fileManager removeItemAtPath:[GlobalVar getFilePath:@"result.txt"] error:&error];
                if (success)
                {
                    [GlobalVar createEditableDataBaseIfNeeded];
                    NSLog(@"删除文件成功!");
                }
            }
        }else
        {
            NSLog(@"上传文件错误信息:%@",[upLoadInfroArr objectAtIndex:1]);
        }
    }
}
-(void)upLoadFail:(ASIHTTPRequest*)request
{
    NSLog(@"上传失败");
}
//弹出更新对话框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 200)
    {
        exit(0);
    }
    
}


-(void)dealloc
{
    [urlsDic release];
    [super dealloc];
}
@end
